<?php

namespace app\common\controller;

use think\Controller;
use think\Request;
use think\Response;
use Dm\Request\V20151123\SingleSendSmsRequest;
use app\common\model\Sms;
use think\Loader;
Loader::import('extend/aliyun-php-sdk-dm/aliyun-php-sdk-core/Config.php');
include_once EXTEND_PATH.'aliyun-php-sdk-dm/aliyun-php-sdk-core/Profile/DefaultProfile.php';
include_once EXTEND_PATH.'aliyun-php-sdk-dm/aliyun-php-sdk-core/DefaultAcsClient.php';
include_once EXTEND_PATH.'aliyun-php-sdk-dm/aliyun-php-sdk-dm/Dm/Request/V20151123/SingleSendSmsRequest.php';
class CaptchaController extends Controller
{
	protected $Success = true;
	protected $Msg = "";
   
    //获取验证码
    public function getCaptcha($mobile)
    {
    		$code = $this->randString();   //验证码生成
    	//验证码发送
    		$iClientProfile = \DefaultProfile::getProfile("cn-hangzhou", "OvdEH9l5SynTu3Dm", "NBjtdQW6HDqPRaWNomnZkM1NXruSVP");
    		$client = new \DefaultAcsClient($iClientProfile);
    		$request = new SingleSendSmsRequest();
    		$request->setSignName("海棠金融");  //管理控制台中配置的短信签名（状态必须是验证通过）
    		$request->setActionName("SingleSendSms"); //操作接口名，系统规定参数，取值：SingleSendSms
    		$request->setTemplateCode("SMS_13260232"); //管理控制台中配置的审核通过的短信模板的模板CODE（状态必须是验证通过）
    		$request->setRecNum($mobile); //RecNum 目标手机号，多个手机号可以逗号分隔
    		$arr = json_encode(["vercode"=>$code]);
    		$request->setRegionId("cn-hangzhou");
    		$request->setParamString($arr); //短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。 例如:短信模板为：“接受短信验证码${no}”,此参数传递{“no”:”123456”}，用户将接收到[短信签名]接受短信验证码123456
    		
    	if($this->Success && $response = $client->getAcsResponse($request))
    	{
    		$data = array(
    				'mobile'=>$mobile,
    				'captcha'=>$code,
    				'createtime'=>time(),
    				'expiretime'=>time()+300    //有效时间
    		);
    		if((new Sms())->save($data))
    		{
    			$this->Success = true;
    			$this->Msg = "验证码已发送!";
    			return $this->response(['Success'=>$this->Success,'Msg'=>$this->Msg]);
    		}else{
    			$this->Success = false;
    			$this->Msg = "系统繁忙，请稍后重试!";
    			return $this->response(['Success'=>$this->Success,'Msg'=>$this->Msg]);
    		}
    	}else{
    		$this->Success = false;
    		$this->Msg = "系统繁忙，请稍后重试!";
    		return $this->response(['Success'=>$this->Success,'Msg'=>$this->Msg]);
    	}
    
    }
    
    //验证码生成
    protected static function randString($len = 6)
    {
    	$chars = str_repeat('0123456789', $len);
    	$chars = str_shuffle($chars);
    	$str   = substr($chars, 0, $len);
    	return $str;
    }
    
    protected function response($data, $type = 'json', $code = 200)
    {
    	return Response::create($data, $type,200,['Access-Control-Allow-Origin'=>'*'])->code($code);
    }
}
